package com.shop.service;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shop.entity.CommonUser;
import com.shop.entity.MerchantMerchant;
import com.shop.mapper.MerchantMapper;
import com.shop.model.PageParam;
import com.shop.model.vo.Rsp;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @BelongsProject: shop
 * @BelongsPackage: com.shop.service
 * @Author: 尹标
 * @CreateTime: 2020-11-25 10:17
 * @Description: 商户 业务层
 */
@Service
@AllArgsConstructor
public class MerchantService {

    private MerchantMapper merchantMapper;

    public PageInfo<MerchantMerchant> searchMerchantPage(PageParam<MerchantMerchant> pageParam) {
        if (!StringUtils.isEmpty(pageParam.getSuperSearchKeyWord())) {
            //执行高级检索
            //分页
            PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
            //排序
            for (int i = 0; i < pageParam.getOrderParams().length; i++) {
                PageHelper.orderBy(pageParam.getOrderParams()[i]);
            }
            return new PageInfo<MerchantMerchant>(merchantMapper.superSearch(pageParam.getSuperSearchKeyWord()));
        }
        PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        //排序
        for (int i = 0; i < pageParam.getOrderParams().length; i++) {
            PageHelper.orderBy(pageParam.getOrderParams()[i]);
        }
        return new PageInfo<MerchantMerchant>(merchantMapper.queryAllByModel(pageParam.getModel()));
    }

    /**
     * 修改商户状态
     *
     * @param merchantMerchant
     * @return
     */
    public Rsp changeStatus(MerchantMerchant merchantMerchant) {
        //获取当前状态
        String merchantStatus = merchantMerchant.getMerchantStatus();
        //保存修改结果
        Integer result;
        //如果是1 改为0
        if (merchantStatus.equals("0")) {
            merchantMerchant.setMerchantStatus("0");
            result = merchantMapper.changeStatus(merchantMerchant);
        } else {
            merchantMerchant.setMerchantStatus("1");
            result = merchantMapper.changeStatus(merchantMerchant);
        }
        //发送短信服务
        //获取账户,密码,手机号
        String account = merchantMerchant.getAccount();
        CommonUser userByAccount = merchantMapper.getUserByAccount(account);
        String password = userByAccount.getPassword();

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4GEjqAouL4gBUsHB31tw", "2rFH17ElfbYpCjiPrPs9daIRoR4btn");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", merchantMerchant.getMerchantPhone());
        request.putQueryParameter("SignName", "阿标java商城");
        request.putQueryParameter("TemplateCode", "SMS_205471958");
        //获取随机验证码
        System.out.println(account + "============" + password);
        request.putQueryParameter("TemplateParam", "{code:" + password + "}");
        CommonResponse response = null;
        try {
            response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (Exception e) {
            e.printStackTrace();
        }


        if (result > 0) {
            return Rsp.success(merchantMerchant).msg("修改成功");
        } else {
            return Rsp.fail();
        }
    }

    /**
     * 修改商户审核状态开关
     */
    public Rsp changeExamineStatus(MerchantMerchant merchantMerchant) {
        //获取当前状态
        String merchantStatus = merchantMerchant.getExamineStatus();
        //保存修改结果
        Integer result;
        //如果是1 改为0
        if (merchantStatus.equals("0")) {
            merchantMerchant.setMerchantStatus("0");
            result = merchantMapper.changeExamineStatus(merchantMerchant);
        } else {
            merchantMerchant.setMerchantStatus("1");
            result = merchantMapper.changeExamineStatus(merchantMerchant);
        }
        if (result > 0) {
            return Rsp.success(merchantMerchant).msg("修改成功");
        } else {
            return Rsp.fail();
        }
    }

    public MerchantMerchant getMerchantInfoByLoginId(Integer merchantId) {
        MerchantMerchant merchantMerchant = merchantMapper.selectById(merchantId);
        System.out.println(merchantMerchant.toString());
        return merchantMerchant;
    }

    /**
     * 逻辑删除商户
     *
     * @param merchantMerchant
     * @return
     */
    public Rsp deleteOne(MerchantMerchant merchantMerchant) {
        //获取商户id
        Integer id = merchantMerchant.getId();
        Integer deleteOne = merchantMapper.deleteOne(id);
        return deleteOne > 0 ?
                Rsp.success(merchantMerchant).msg("删除成功")
                : Rsp.fail().msg("请求异常");
    }


    /**
     * 添加商户账号
     *
     * @param merchant
     * @return
     */
    @Transactional
    public Rsp insertOne(MerchantMerchant merchant) {
        //写入common_user账户表
        String account = merchant.getAccount();
        String merchantPhone = merchant.getMerchantPhone();
        //判断账户是否存在
        Integer accountIsExist = merchantMapper.accountIsExist(account);
        //判断手机号是否重复
        Integer phoneIsExist = merchantMapper.phoneIsExist(merchantPhone);

        //判断重复
        if (accountIsExist > 0 || phoneIsExist > 0) {
            return Rsp.fail().msg("用户名或电话号码重复");
        }

        CommonUser commonUser = new CommonUser();

        //设置账户
        commonUser.setAccount(account);
        //获取随机数字
        int num = (int) ((Math.random() * 9 + 1) * 100000);
        //设置六位随机密码
        commonUser.setPassword(num + "");
        //设置角色
        commonUser.setRole("merchant");
        Integer addUser = merchantMapper.addCommonUser(commonUser);
        //设置自动生成的主键
        merchant.setUserId(commonUser.getId());
        //设置商户号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = sdf.format(new Date());
        merchant.setMerchantNumber("MER" + format + UUID.randomUUID().toString().substring(0, 4));
        //写入商户表
        Integer addMerchant = merchantMapper.insertOne(merchant);
        //设置随机商户号
        return Rsp.success(addMerchant).msg("添加成功");
    }
}
